package handler.wx

import service.wx.WxApi
import service.wx.WxPay
import service.wx.WxSignature

import org.paic.d.D

import service.store.ind.SockClientInfo

handler.post('/wx/pay/notify'){req, resp ->
	log.warn('wx-pay-notify')

	// 接收xml
	req.bodyHandler{body -> 
		final String encoding  = 'utf-8'
		XmlParser parser = new XmlParser()

		try{
			// 解析xml
			def root = parser.parseText(new String(body.bytes, encoding))

/* eg.
<xml><appid><![CDATA[wx9f7507a78aa0c8f0]]></appid>
<bank_type><![CDATA[CFT]]></bank_type>
<cash_fee><![CDATA[100]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[Y]]></is_subscribe>
<mch_id><![CDATA[1233859202]]></mch_id>
<nonce_str><![CDATA[mp537kz1jebyqy30jygiptkuvowzoaa7]]></nonce_str>
<openid><![CDATA[oQMltt6f8dgCfkst6T5f-T7BEawk]]></openid>
<out_trade_no><![CDATA[0ef3crst3bt25xvahogq0t1k7rw2nnse]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[273A44B55DD19EF32E795113DB76CDE0]]></sign>
<time_end><![CDATA[20150609204512]]></time_end>
<total_fee>100</total_fee>
<trade_type><![CDATA[JSAPI]]></trade_type>
<transaction_id><![CDATA[1009200005201506090229390894]]></transaction_id>
</xml>
*/

			Map<String, String> info = [:]
			info.appid = root.appid.text()
			info.cash_fee = root.cash_fee.text()
			info.total_fee = root.total_fee.text()
			info.fee_type = root.fee_type.text()
			info.openid = root.openid.text()
			info.out_trade_no = root.out_trade_no.text()

			info.result_code = root.result_code.text()
			info.sign = root.sign.text()
			info.transaction_id = root.transaction_id.text()

			log.info('recieve pay notify - ' + info)

			if('SUCCESS' != info.result_code){
				resp.end ''
				return
			}

			// update order status

			List r = []
			r << WxPay.updateOrderStatus('t_peizi_pay_order', info)
			r << WxPay.updateOrderStatus('t_shop_pay_order', info)

			if(r.any{it}){
				String sockid = SockClientInfo.inst.get(info.openid + '-sockid')
				if(sockid){
					handlerSockjs.send(sockid, [action: 'pay-status-refresh'])
				}
			}

			// 返回xml
			def sw = new StringWriter()
			def builder = new groovy.xml.MarkupBuilder(sw)
			builder.xml{
				time('' + new Date().getTime())
				result_code('SUCCESS')
			}

			String returnStr = sw.toString()
			log.info('back message notify - ' + returnStr)
			resp.end(returnStr)
		}catch(ex){
			log.error('wx notify handle error!', ex)
			resp.end ''
		}
	}
}

handler.post('/wx/pay-warn'){req, resp ->
	log.warn('wx-pay-warn')

	req.bodyHandler{body -> 
		final String encoding  = 'utf-8'
		String bodyStr = new String(body.bytes, encoding)
		log.info('recieve pay notify - ' + bodyStr)

		resp.end 'ok'
	}
}

// for test
handler.get('/wx/pay-test/add-order'){req, resp ->
	def params = [:]

	// 以分为单位
	params.totalFee = 1
	params.body = '又一个测试'
	params.attach = 'test'
	params.tradeNo = WxPay.generateNonce()

	params.ip = '8.8.8.8'
	params.openid = 'oQMltt6f8dgCfkst6T5f-T7BEawk'

	def r = WxPay.genPostParams(params)
	String prepayId = WxPay.getPrepayId(r)

	resp.end prepayId
}

handler.get('/wx/pay-test/test'){req, resp ->
	String prepayId = req.params.prepayId
	if(!prepayId){
		resp.end 'no prepayId'
		return 
	}

	def jsPayParams = WxPay.genPayJsParams(prepayId)
	Map r = [:]
	jsPayParams.each{
		r['pay_' + it.key] = it.value
	}

	Map jsapiInfo = WxSignature.getJsapiInfo(WxSignature.conf.urlHost + req.uri)
	r.putAll(jsapiInfo)

	resp.render('/wx/pay-test/bige.html', r)
}